package com.cxdr.awsips.packing.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.cxdr.awsips.packing.bean.Protocol;
import com.cxdr.awsips.packing.bean.StoreModel;
import com.cxdr.awsips.packing.bean.Target;
import com.cxdr.awsips.packing.logger.LogFactory;

/**
 * 链路配置工具栏
 * 
 * @author pugang
 * 
 */
public class LinkConfig {
	private static Logger logger = LogFactory.makeNewLogger(LinkConfig.class);
	private static List<Target> targets = new LinkedList<Target>();
	private static List<Target> sources = new LinkedList<Target>();
	private static StoreModel storeModel = StoreModel.valueOf(SystemConfig.get("link.store"));
	private static Properties globalConfig = new Properties();
	private static Document configDoc = null;
	private static final String CONFIG_FILE_NAME = SystemConfig.get("link.config") + ".xml";
	static {
		load();
	}

	protected synchronized static void load() {
		switch (storeModel) {
		case DATABASE:
			_loadFromDB();
			break;
		case XML:
			_loadFormXML();
			break;
		}
	}

	/**
	 * 设置存储模式，如果不支持某种模式则抛出不支持异常
	 * 
	 * @throws Exception
	 */
	public static void setStoreModel(StoreModel model) throws Exception {
		if (model != StoreModel.DATABASE && model != StoreModel.XML) {
			throw new Exception("不支持此模式");
		}
		storeModel = model;
	}

	private static void _loadFormXML() {
		SAXReader reader = new SAXReader();
		try {
			FileInputStream in = new FileInputStream(System.getProperty("user.dir") + File.separator + CONFIG_FILE_NAME);
			configDoc = reader.read(new InputStreamReader(in, Charset.forName("UTF-8")));
			_loadGlobalXML();
			_loadSourceXML();
			_loadTargetXML();
			configDoc = null;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 加载全局配置
	 */
	private static void _loadGlobalXML() {
		// 配置全局设置
		if (configDoc == null) {
			return;
		}
		List globalNodes = configDoc.selectNodes("/target-config/global/property");
		for (Object obj : globalNodes) {
			Element el = (Element) obj;
			String name = el.attribute("name").getValue().toUpperCase();
			String value = el.getTextTrim();
			if (!value.isEmpty()) {
				globalConfig.setProperty(name.toUpperCase(), value);
			}
		}
	}

	/**
	 * 加载目标配置
	 */
	private static void _loadTargetXML() {
		if (configDoc == null) {
			return;
		}
		// 配置目标全局设置
		Properties targetGlobal = new Properties();
		List globalNodes = configDoc.selectNodes("/target-config/targets/global/property");
		for (Object obj : globalNodes) {
			Element el = (Element) obj;
			String name = el.attribute("name").getValue().toUpperCase();
			String value = el.getTextTrim();
			if (!value.isEmpty()) {
				targetGlobal.setProperty(name.toUpperCase(), value);
			}
		}
		for (Object key : globalConfig.keySet()) {
			if (!targetGlobal.containsKey(key)) {
				targetGlobal.put(key, globalConfig.get(key));
			}
		}
		// 配置单独结点
		List nodes = configDoc.selectNodes("/target-config/targets/target");
		for (Object obj : nodes) {
			Element el = (Element) obj;
			List els = el.elements();
			Target target = new Target();
			target.setUsername(targetGlobal.getProperty("USERNAME"));
			target.setPassword(targetGlobal.getProperty("PASSWORD"));
			target.setPath(targetGlobal.getProperty("PATH"));
			target.setIp(targetGlobal.getProperty("IP"));
			target.setProtocol(Protocol.valueOf(targetGlobal.getProperty("PROTOCOL")));
			for (Object o : els) {
				Element cel = (Element) o;
				String name = cel.getQualifiedName();
				String text = cel.getTextTrim();
				if (name.equalsIgnoreCase("IP")) {
					target.setIp(text);
				}
				if (name.equalsIgnoreCase("path")) {
					target.setPath(text);
				}
				if (name.equalsIgnoreCase("ID")) {
					target.setID(text);
				}
				if (name.equalsIgnoreCase("username")) {
					target.setUsername(text);
				}
				if (name.equalsIgnoreCase("password")) {
					target.setPassword(text);
				}
				if (name.equalsIgnoreCase("PROTOCOL")) {
					for (Protocol p : Protocol.values()) {
						if (p.name().equalsIgnoreCase(text)) {
							target.setProtocol(p);
						}
					}
				}
			}
			targets.add(target);
		}
	}

	/**
	 * 加载目标配置
	 */
	private static void _loadSourceXML() {
		if (configDoc == null) {
			return;
		}
		// 配置源全局设置
		Properties sourceGlobal = new Properties();
		List globalNodes = configDoc.selectNodes("/target-config/sources/global/property");
		for (Object obj : globalNodes) {
			Element el = (Element) obj;
			String name = el.attribute("name").getValue().toUpperCase();
			String value = el.getTextTrim();
			if (!value.isEmpty()) {
				sourceGlobal.setProperty(name.toUpperCase(), value);
			}
		}
		for (Object key : globalConfig.keySet()) {
			if (!sourceGlobal.containsKey(key)) {
				sourceGlobal.put(key, globalConfig.get(key));
			}
		}
		// 配置单独结点
		List nodes = configDoc.selectNodes("/target-config/sources/target");
		for (Object obj : nodes) {
			Element el = (Element) obj;
			List els = el.elements();
			Target source = new Target();
			source.setUsername(sourceGlobal.getProperty("USERNAME"));
			source.setPassword(sourceGlobal.getProperty("PASSWORD"));
			source.setPath(sourceGlobal.getProperty("PATH"));
			source.setIp(sourceGlobal.getProperty("IP"));
			source.setProtocol(Protocol.valueOf(sourceGlobal.getProperty("PROTOCOL")));
			for (Object o : els) {
				Element cel = (Element) o;
				String name = cel.getQualifiedName();
				String text = cel.getTextTrim();
				if (name.equalsIgnoreCase("IP")) {
					source.setIp(text);
				}
				if (name.equalsIgnoreCase("path")) {
					source.setPath(text);
				}
				if (name.equalsIgnoreCase("ID")) {
					source.setID(text);
				}
				if (name.equalsIgnoreCase("username")) {
					source.setUsername(text);
				}
				if (name.equalsIgnoreCase("password")) {
					source.setPassword(text);
				}
				if (name.equalsIgnoreCase("backpath")) {
					source.setBackpath(text);
				}
				if (name.equalsIgnoreCase("protocol")) {
					for (Protocol p : Protocol.values()) {
						if (p.name().equalsIgnoreCase(text)) {
							source.setProtocol(p);
						}
					}
				}
			}
			sources.add(source);
		}
	}

	private static void _loadFromDB() {

	}

	public static List<Target> getSources() {
		return sources;
	}

	public static void setSources(List<Target> sources) {
		LinkConfig.sources = sources;
	}

	public static List<Target> getTargets() {
		return targets;
	}

	public static void setTargets(List<Target> targets) {
		LinkConfig.targets = targets;
	}

	public static StoreModel getStoreModel() {
		return storeModel;
	}

	public static int getTargetSize() {
		return targets.size();
	}

	public static void main(String args[]) {
		for (Target t : LinkConfig.getTargets()) {
			System.out.println(t.getID());
			System.out.println(t.getPath());
			System.out.println(t.getProtocol());
			System.out.println(t.getUsername());
			System.out.println(t.getIp());
			System.out.println("---------------------");
		}
		Protocol.values();
	}
}
